﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SerialPortHelperLib;
using System.IO.Ports;
using System.Threading;
using XChipTool.Enties;
using System.Configuration;
using XChip_Common;
using BinAnalysisHelp;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using AdbService;

namespace XChipTool.Full
{
    public partial class XChip_AF : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        private int pointX = 20;
        private int pointY = 50;

        private int pointX2 = 60;
        private int pointY2 = 60;

        private bool isRead = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        private bool isWrite = false;
        private addressregisterManager aBll;
        private List<addressregister> XChipAf;
        private static XChip_AF _instance;

        public addressregisterManager Addr_dal;
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;

        public int buffer = 64;

        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;

        public static XChip_AF Instance(SerialPort _sPortTemp ,addressregisterManager _aBll)
        {
            if (_instance == null)
            {
                _instance = new XChip_AF(_sPortTemp, _aBll);
            }
            return _instance;
        }
        public XChip_AF(SerialPort _sPortTemp , addressregisterManager _aBll)
        {
            
            sPortTemp = _sPortTemp;
            //pictureBox1.Paint += new PaintEventHandler(PictureBox1_Paint);
            aBll = _aBll;
            XChipAf = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "af" || c.Classify == "Common"));
            InitializeComponent();
            // 初始化Timer  
            myTimer = new System.Timers.Timer();
            // 设置Timer的间隔为50毫秒  
            myTimer.Interval = 50;
            // 设置Timer的Elapsed事件  
            myTimer.Elapsed += OnTimedEvent;

        }
        private System.Timers.Timer myTimer;
        private void PictureBox1_Paint(object sender, PaintEventArgs e)
        {
            using (Pen dashedPen = new Pen(Color.Black, 1))
            {
                dashedPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

                // 获取PictureBox的图形对象  
                Graphics g = e.Graphics;

                // 绘制X轴（从左边到右边）  
                int xAxisY = pictureBox1.Height - 1; // 贴紧底部  
                g.DrawLine(Pens.Black, 0, xAxisY, pictureBox1.Width, xAxisY);

                // 绘制Y轴（从底部到顶部）  
                int yAxisX = 0; // 贴紧左边  
                g.DrawLine(Pens.Black,  0, yAxisX, yAxisX, pictureBox1.Height);

                // 绘制点  
                g.FillEllipse(Brushes.Red, pointX - 3, pointY - 3, 6, 6);

                // 绘制到X轴的虚线  
                g.DrawLine(dashedPen, pointX, pointY, pointX, xAxisY);

                // 绘制到Y轴的虚线
                g.DrawLine(dashedPen, pointX, pointY, yAxisX, pointY);


                // 绘制点  
                g.FillEllipse(Brushes.Red, pointX2 - 3, pointY2 - 3, 6, 6);

                // 绘制到X轴的虚线  
                g.DrawLine(dashedPen, pointX2, pointY2, pointX2, xAxisY);

                // 绘制到Y轴的虚线
                g.DrawLine(dashedPen, pointX2, pointY2, yAxisX, pointY2);

            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            //pictureBox1.Invalidate();
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            List<long> aaa = new List<long>();

            // 开始计时  
            stopwatch.Start();

            // 使用信号量限制并发数量（例如最多同时10个请求）
            var semaphore = new SemaphoreSlim(10);
            var tasks = new List<Task<byte>>();

            for (int i = 0; i < 200; i++)
            {
                tasks.Add(ReadRegisterWithSemaphoreAsync("20000021", semaphore));
            }

            // 等待所有任务完成
            var results = await Task.WhenAll(tasks);

            // 将结果添加到列表中
            aaa.AddRange(results.Select(r => (long)r));

            stopwatch.Stop();
            var aaas = stopwatch.ElapsedMilliseconds;
            TimeSpan ts = stopwatch.Elapsed;
            var aaaaa = ts.Seconds;

            int[] a = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
            int[] b = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            chart1.Series[0].Points.DataBindXY(a, b);
        }

        // 使用信号量控制并发数量的辅助方法
        private async Task<byte> ReadRegisterWithSemaphoreAsync(string address, SemaphoreSlim semaphore)
        {
            await semaphore.WaitAsync();
            try
            {
                return (byte)await ReadRegisterAsync(address);
            }
            finally
            {
                semaphore.Release();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            int[] a = new int[] { 2500, 2200, 2700, 1400, 2500, 2900, 2700, 1800, 1200,2700,5990,2400,2670,1200 ,4900,4200,4500,4600,1200,4000};
            int[] b = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14 ,15,16,17,18,19,20};
            chart2.Series[0].Points.DataBindXY(b, a);
        }

        private async void Motor_ID_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
               await SetAfRegister(model, Val);
            }
        }

        private void Motor_set_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                _ = SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                _ = SetAfRegister(model, Val);
            }
        }
        private async Task SetAfRegister(addressregister model, ulong add, bool isCheck = true)
        {
          
            if (isRead) return;
            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetAfRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }

        }

        private void s_nT_LastContastRatio_sad_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            var Triggerflagsbitlist = GetSetBitsPositions(Triggerflags.Text);
            for (int i = 0; i < 8; i++)
            {
                var triggen = this.Controls.Find("triggen" + i, true);
                if (Triggerflagsbitlist.Any(c => c == i))
                {
                    (triggen[0] as CheckEdit).Checked = true;
                    (triggen[0] as CheckEdit).ForeColor = Color.Red;
                }
                else
                {
                    (triggen[0] as CheckEdit).Checked = false;
                    (triggen[0] as CheckEdit).ForeColor = Color.Black;
                }

            }
            var theenablebitbitlist = GetSetBitsPositions(theenablebit.Text);
            for (int i = 0; i < 8; i++)
            {
                var Enableen = this.Controls.Find("Enableen" + i, true);
                if (theenablebitbitlist.Any(c => c == i))
                {
                    (Enableen[0] as CheckEdit).Checked = true;
                    (Enableen[0] as CheckEdit).ForeColor = Color.Red;
                }
                else
                {
                    (Enableen[0] as CheckEdit).Checked = false;
                    (Enableen[0] as CheckEdit).ForeColor = Color.Black;
                }

            }
        }

        private void nT_Compare_Offset_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
        }

        private void s_nT_LastContastRatio_sad_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                s_nT_LastContastRatio_sad_Leave(sender, null);
            }
        }

        private void nT_Compare_Offset_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                nT_Compare_Offset_Leave(sender, null);
            }
        }

        private void Motor_ID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Motor_ID_Leave(sender, null);
            }
        }

        private void Motor_set_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Motor_set_Leave(sender, null);
            }
        }

        private async void simpleButton5_Click(object sender, EventArgs e)
        {
            try
            {
                //if (IsUsbOpen || m_open)
                //{

                //}
                //else
                //{
                //    if (!sPortTemp.IsOpen)
                //    {
                //        DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                //        return;
                //    }
                //}
                isRead = true;
                WaitBefore.Start("读取中", "正在加载中", 10);
                // 记录开始时间和寄存器计数
                var startTime = DateTime.Now;
                int totalRegisterCount = 0;
                List<string> NameList = new List<string>();
                //放在下面特殊处理
                NameList.Add("ctt_hill_th_dn");
                for (int i = 0; i < XChipAf.Count; i++)
                {
                    if (XChipAf[i].NameType.ToLower().Contains("CoarseMinStepR".ToLower()))
                    {

                    }
                    var type = AppHelper.NameTypeToString(XChipAf[i].NameType);
                    if (NameList.Exists(c => c.ToLower() == (type)))
                    {
                        continue;
                    }
                    ////加上单选框的_en
                    //if (xChipHDRAe[i].ControlType == "1")
                    //{
                    //    type = xChipHDRAe[i].NameType;
                    //}
                    var col = Controls_Find(type);

                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            var nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();

                            if (item.Name.ToString().ToLower()== "CoarseMinStepR".ToLower())
                            {
                                nList = XChipAf.Where(c => c.NameType.ToLower()==item.Name.ToString().ToLower() && c.ControlType == "0").ToList();

                            }
                            if (nList.Count == 0)
                            {
                                nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else
                            {
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }
                        NameList.Add(item.Name);

                    }

                    //NameList.Add(type);
                }
                ctt_hill_th_dn.Text = (await  GetAFRegister("ctt_hill_th_dn_h")).ToString("X2") + (await GetAFRegister("ctt_hill_th_dn_l")).ToString("X2");
                textEdit4.Text = nMinThr.Text;
                AFModeComBox.Text = (await GetAFRegister("AF_Mode")).ToString("X2");
                isRead = false;
                if (Convert.ToUInt32(AFModeComBox.Text, 16) == 2)
                {
                    HIGH_PRE.Enabled = true;
                    manualpos.Enabled = true;
                }
                else
                {
                    HIGH_PRE.Enabled = false;
                    manualpos.Enabled = false;
                }
                if (Convert.ToUInt32(manualpos.Text, 16) > 0x3ff)
                {
                    HIGH_PRE.Value = 0x3ff;
                }
                else
                {
                    HIGH_PRE.Value = Convert.ToInt32(manualpos.Text, 16);
                }
                MotorCurrentRedraw();
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("出现错误信息：" + ex.ToString());

            }
            finally
            {
                isRead = false;
                WaitBefore.Close();
                
            }
        }
        private Control[] Controls_Find(string str)
        {
            //var t =   this.Controls.Find(type, true);
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower().Contains(str.ToLower()) && !listc.Exists(c => c.Name.ToLower() == (fieldInfo[i].Name.ToLower())))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    //break;
                }
            }
            return listc.ToArray();
        }


        #region ADB异步读写


        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read", 500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values, 16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }




        #endregion








        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                
                isRead = true;
                WaitBefore.Start("读取中", "正在加载中", 10);
                // 记录开始时间和寄存器计数
                var startTime = DateTime.Now;
                int totalRegisterCount = 0;
                List<string> NameList = new List<string>();

                for (int i = 0; i < XChipAf.Count; i++)
                {
                    if (XChipAf[i].NameType.Contains("nT_HistDvalueRatio_1X"))
                    {

                    }
                    var type = AppHelper.NameTypeToString(XChipAf[i].NameType);
                    if (NameList.Exists(c => c.ToLower() == (type)))
                    {
                        continue;
                    }
                    ////加上单选框的_en
                    //if (xChipHDRAe[i].ControlType == "1")
                    //{
                    //    type = xChipHDRAe[i].NameType;
                    //}
                    var col = Controls_Find(type);

                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            var nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            if (nList.Count == 0)
                            {
                                nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else
                            {
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }
                        NameList.Add(item.Name);

                    }

                    //NameList.Add(type);
                }
                textEdit4.Text = nMinThr.Text;
               
                var Triggerflagsbitlist = GetSetBitsPositions(Triggerflags.Text);
                for (int i = 0; i < 8; i++)
                {
                    var triggen = this.Controls.Find("triggen" + i, true);
                    if (Triggerflagsbitlist.Any(c => c == i))
                    {
                        (triggen[0] as CheckEdit).Checked = true;
                        (triggen[0] as CheckEdit).ForeColor = Color.Red;
                    }
                    else
                    {
                        (triggen[0] as CheckEdit).Checked = false;
                        (triggen[0] as CheckEdit).ForeColor = Color.Black;
                    }

                }
                var theenablebitbitlist = GetSetBitsPositions(theenablebit.Text);
                for (int i = 0; i < 8; i++)
                {
                    var Enableen = this.Controls.Find("Enableen" + i, true);
                    if (theenablebitbitlist.Any(c => c == i))
                    {
                        (Enableen[0] as CheckEdit).Checked = true;
                        (Enableen[0] as CheckEdit).ForeColor = Color.Red;
                    }
                    else
                    {
                        (Enableen[0] as CheckEdit).Checked = false;
                        (Enableen[0] as CheckEdit).ForeColor = Color.Black;
                    }

                }
                isRead = false;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("出现错误信息：" + ex.ToString());

            }
            finally
            {
                isRead = false;
                WaitBefore.Close();
            }
        }

        private void DACMin_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (txtEdit.Name.ToLower() == "DACMax".ToLower() && Convert.ToInt32(txtEdit.Text,16) == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("DACMax值不能为0");
                return;
            }
            if (txtEdit.Name.ToLower() == "DACMin".ToLower() && Convert.ToInt32(txtEdit.Text, 16) == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("DACMin值不能为0");
                return;
            }
            if (Convert.ToInt32(DACMax.Text, 16) < Convert.ToInt32(DACMin.Text, 16))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("DACMax值不能小于DACMin");
                return;
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            MotorFullRange.Text = (Convert.ToInt32(DACMax.Text,16) - Convert.ToInt32(DACMin.Text,16)).ToString("X2");
            MotorFullRange_Leave(null,null);
            MotorCurrentRedraw();
        }

        public async void MotorCurrentRedraw()
        {
            chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

            chart3.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            chart3.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            chart3.Series[0].BorderWidth = 3;
            chart3.Series[0].Color = Color.Red;
            int[] Y = new int[] { Convert.ToInt32(DACMin.Text,16), Convert.ToInt32(DACMax.Text, 16) };
            int[] X = new int[] { Convert.ToInt32(MotorOffsetMin.Text, 16), Convert.ToInt32(MotorFullRange.Text, 16), };
            chart1.Series[0].Points.DataBindXY(X, Y);
            chart1.Series[0].BorderWidth = 3;
            chart1.Series[0].Color = Color.Red;

            var H = (await ReadRegisterAsync(0x80300006.ToString("X"))).ToString("X2");
            var L = (await ReadRegisterAsync(0x80300007.ToString("X"))).ToString("X2");
            var AxisX = Convert.ToInt32((H + L), 16);
            H = (await ReadRegisterAsync(0x80300008.ToString("X"))).ToString("X2");
            L = (await ReadRegisterAsync(0x80300009.ToString("X"))).ToString("X2");
            var AxisY = Convert.ToInt32((H + L), 16);
            
            chart3.ChartAreas[0].AxisX.Interval = AxisX / 10;
            chart3.ChartAreas[0].AxisY.Interval = AxisY / 10;
            chart3.ChartAreas[0].AxisX.Maximum = AxisX;
            chart3.ChartAreas[0].AxisY.Maximum = AxisY;
            //a = new int[] { 3000,3000,2000,2000,3000 };
            //b = new int[] { 1000,2000 ,2000,1000,1000};

            Y = new int[] { Convert.ToInt32(winstartY.Text, 16),
                Convert.ToInt32(winstartY.Text, 16),
                Convert.ToInt32(winstartY.Text, 16) + Convert.ToInt32(winheight.Text, 16),
                Convert.ToInt32(winstartY.Text, 16) + Convert.ToInt32(winheight.Text, 16),
                Convert.ToInt32(winstartY.Text, 16) };
            X = new int[] { Convert.ToInt32(winstartX.Text, 16),
                Convert.ToInt32(winstartX.Text, 16) + Convert.ToInt32(winwidth.Text, 16),
                Convert.ToInt32(winstartX.Text, 16) + Convert.ToInt32(winwidth.Text, 16),
                Convert.ToInt32(winstartX.Text, 16) ,
                Convert.ToInt32(winstartX.Text, 16) };

            chart3.Series[0].Points.DataBindXY(X, Y);
           
        }

        private void ctt_hill_th_up_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
        }

        private void ctt_hill_ratio_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
        }

        private void ctt_hill_th_up_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ctt_hill_th_up_Leave(sender, null);
            }
        }

        private void ctt_hill_ratio_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ctt_hill_ratio_Leave(sender, null);
            }
        }

        private void MotorOffsetMin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                MotorOffsetMin_Leave(sender, null);
            }
        }

        private void textEdit4_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAf.Exists(c => c.NameType.ToLower() == $"nMinThr".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"nMinThr".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            isRead = true;
            nMinThr.Text = txtEdit.Text;
            textEdit4.Text = txtEdit.Text;
            isRead = false;
        }

        private void textEdit4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                textEdit4_Leave(sender, null);
            }
           
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();//将打开的地址给ofd
            openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
            if (openFileDialog.ShowDialog() == DialogResult.OK)//用户是否选择确定
            {
                StreamReader sr = new StreamReader(openFileDialog.FileName);
                string tempStr = string.Empty;
                List<string> tempStrList = new List<string>();
                int Number = 0;
                while ((tempStr = sr.ReadLine()) != null)
                {
                    tempStr = tempStr.Trim().Replace(",", "").Replace("，", "").Replace("0x", "").Replace(" ", "");
                    string addr = tempStr.Substring(0,4);
                    // 取前4位作为寄存器
                    if (IsHexString(addr))
                    {
                        // 取剩下的作为注释
                        string exegesis = tempStr.Substring(4);
                        tempStrList.Add(addr + "," + exegesis);
                        Number++;
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show($"大约在第{tempStr}行出现错误无法转换！请检查！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        sr.Dispose();
                        return;
                    }
                   
                }
                sr.Dispose();
                try
                {
                    List<addressregister> lista = new List<addressregister>();
                    Addr_dal = new addressregisterManager();
                    var aaa = Addr_dal.GetType();
                    //根据注释在数据库中修改寄存器
                    for (int i = 0; i < tempStrList.Count(); i++)
                    {
                        var exegesis = tempStrList[i].Split(',')[1].ToLower();
                        var addrlist = Addr_dal.GetList(c => c.Register_Name.ToLower() == exegesis.ToLower() && c.Classify.ToLower() == "af");
                        if (addrlist.Count() != 0)
                        {
                            for (int j = 0; j < addrlist.Count(); j++)
                            {
                                addrlist[j].Address = "2000" + tempStrList[i].Split(',')[0];
                                Addr_dal.Update(addrlist[j]);
                            }
                        }
                    }
                    XtraMessageBox.Show("修改成功！请重启软件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //根据寄存器在数据库中修改注释
                    //for (int i = 0; i < tempStrList.Count(); i++)
                    //{
                    //    var addr = "2000" + tempStrList[i].Split(',')[0].ToLower();
                    //    var addrlist = Addr_dal.GetList(c => c.Address.ToLower() == addr && c.Classify.ToLower() == "af");
                    //    if (addrlist.Count() != 0)
                    //    {
                    //        for (int j = 0; j < addrlist.Count(); j++)
                    //        {
                    //            addrlist[j].Register_Name = tempStrList[i].Split(',')[1];
                    //            Addr_dal.Update(addrlist[j]);
                    //        }

                    //    }
                    //}
                }
                catch (Exception ex)
                {

                    throw;
                }
                
                
            }
        }
        static bool IsHexString(string input)
        {
            int y;
            // 尝试将输入的字符串解析为十六进制数字
            bool isValidHex = int.TryParse(input, System.Globalization.NumberStyles.HexNumber, null, out y);
            return isValidHex;
        }

        private async void simpleButton4_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsUsbOpen || m_open)
                {

                }
                else
                {
                    if (!sPortTemp.IsOpen)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                        return;
                    }
                }
                isRead = true;
                WaitBefore.Start("读取中", "正在加载中", 10);
                // 记录开始时间和寄存器计数
                var startTime = DateTime.Now;
                int totalRegisterCount = 0;
                List<string> NameList = new List<string>();
                //放在下面特殊处理
                NameList.Add("ctt_hill_th_dn");
                for (int i = 0; i < XChipAf.Count; i++)
                {
                    if (XChipAf[i].NameType.Contains("ctt_hill_th_dn"))
                    {

                    }
                    var type = AppHelper.NameTypeToString(XChipAf[i].NameType);
                    if (NameList.Exists(c => c.ToLower() == (type)))
                    {
                        continue;
                    }
                    ////加上单选框的_en
                    //if (xChipHDRAe[i].ControlType == "1")
                    //{
                    //    type = xChipHDRAe[i].NameType;
                    //}
                    var col = Controls_Find(type);

                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            var nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            if (nList.Count == 0)
                            {
                                nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else
                            {
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }
                        NameList.Add(item.Name);

                    }

                    //NameList.Add(type);
                }
                textEdit4.Text = nMinThr.Text;
                MotorCurrentRedraw();
                ctt_hill_th_dn.Text = (await GetAFRegister("ctt_hill_th_dn_h")).ToString("X2") + (await GetAFRegister("ctt_hill_th_dn_l")).ToString("X2");
                int ctt_hill_th_hugetex = 0;
                if (Convert.ToInt32(cct_pre.Text, 16) != 0)
                {
                    ctt_hill_th_hugetex = Convert.ToInt32(cct_pre.Text, 16) * Convert.ToInt32(ctt_hill_ratio.Text, 16) >> 6;
                }
                ctt_hill_th_hugetex = ctt_hill_th_hugetex > Convert.ToInt32(ctt_hill_th_dn.Text, 16) ? ctt_hill_th_hugetex : Convert.ToInt32(ctt_hill_th_dn.Text, 16);
                ctt_hill_th_hugetex = ctt_hill_th_hugetex < Convert.ToInt32(ctt_hill_th_up.Text, 16) ? ctt_hill_th_hugetex : Convert.ToInt32(ctt_hill_th_up.Text, 16);
                ctt_hill_th_huge.Text = ctt_hill_th_hugetex.ToString("X2");

                int dif_contrastint = 0;
                int s_nCurrContrast = Convert.ToInt32((await ReadRegisterAsync(0x20000add.ToString("X"))).ToString("X2") + (await ReadRegisterAsync(0x20000adc.ToString("X"))).ToString("X2"), 16);
                int s_nPreContrast = Convert.ToInt32((await ReadRegisterAsync(0x20000adf.ToString("X"))).ToString("X2") + (await ReadRegisterAsync(0x20000ade.ToString("X"))).ToString("X2"), 16);
                if (s_nCurrContrast > s_nPreContrast)
                {
                    dif_contrastint = s_nCurrContrast - s_nPreContrast;
                }
                dif_contrast.Text = dif_contrastint.ToString("X2");
                simpleButton10_Click(null, null);
                isRead = false;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("出现错误信息：" + ex.ToString());

            }
            finally
            {
                isRead = false;
                WaitBefore.Close();

            }
        }

        private async Task<long> GetAFRegister(string nameType)
        {
           
            if (XChipAf.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                long var = await ReadRegisterAsync(XChipAf.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }

        private async void simpleButton7_Click(object sender, EventArgs e)
        {
            simpleButton4_Click(null, null);
            int ctt_hill_th_hugetex = 0;
            if (Convert.ToInt32(cct_pre.Text, 16) != 0)
            {
                ctt_hill_th_hugetex = Convert.ToInt32(cct_pre.Text, 16) * Convert.ToInt32(ctt_hill_ratio.Text, 16) >> 6;
            }
            ctt_hill_th_hugetex = ctt_hill_th_hugetex > Convert.ToInt32(ctt_hill_th_dn.Text, 16) ? ctt_hill_th_hugetex : Convert.ToInt32(ctt_hill_th_dn.Text, 16);
            ctt_hill_th_hugetex = ctt_hill_th_hugetex < Convert.ToInt32(ctt_hill_th_up.Text, 16) ? ctt_hill_th_hugetex : Convert.ToInt32(ctt_hill_th_up.Text, 16);
            ctt_hill_th_huge.Text = ctt_hill_th_hugetex.ToString("X2");

            int dif_contrastint = 0;
            int s_nCurrContrast = Convert.ToInt32((await ReadRegisterAsync(0x20000add.ToString("X"))).ToString("X2") + (await ReadRegisterAsync(0x20000adc.ToString("X"))).ToString("X2"),16);
            int s_nPreContrast = Convert.ToInt32((await ReadRegisterAsync(0x20000adf.ToString("X"))).ToString("X2") + (await ReadRegisterAsync(0x20000ade.ToString("X"))).ToString("X2"), 16);
            if (s_nCurrContrast > s_nPreContrast)
            {
                dif_contrastint = s_nCurrContrast - s_nPreContrast;
            }
            dif_contrast.Text = dif_contrastint.ToString("X2");
        }

        private  void button3_Click_1(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textEdit1.Text)) { return; }
            if (textEdit1.Text.Length != 8)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"请输入正确的寄存器地址");
                return;
            }
            if (!string.IsNullOrEmpty(textEdit3.Text))
            {
                if (textEdit3.Text.Length != 8)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show($"请输入正确的寄存器地址");
                    return;
                }
                addr2 = Convert.ToUInt32((textEdit3.Text).Replace(" ", ""), 16);
            }
            monitoringlist = new List<string>();
            button3.Enabled = false;
            textEdit2.Enabled = false;
            addr = Convert.ToUInt32((textEdit1.Text).Replace(" ", ""), 16);
            
            myTimer.Start();
        }
        int sum = 0;
        uint addr = 0;
        uint addr2 = 0;
        List<string> monitoringlist = new List<string>();
        private  void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
        { 
            Startmonitoring();
        }
        private  void Startmonitoring()
        {
            try
            {
             this.Invoke((MethodInvoker)async delegate
             {
                 if (string.IsNullOrEmpty(textEdit1.Text)) { return; }
                 string addrstr = "";
                 switch (radioGroup2.SelectedIndex)
                 {
                     case 0:
                         var add = (await ReadRegisterAsync(addr.ToString("X"))).ToString("X2");
                         addrstr = textEdit1.Text + ",0x" + add;
                         monitoringlist.Add(textEdit1.Text + "," + add );
                         break;
                     case 1:
                         if (radioGroup1.SelectedIndex == 0)
                         {
                             var l = (await ReadRegisterAsync(addr.ToString("X"))).ToString("X2");
                             var h = (await ReadRegisterAsync((addr + 1).ToString("X"))).ToString("X2");
                             addrstr = textEdit1.Text + ",0x" + h + l;
                             monitoringlist.Add(textEdit1.Text + "," + h + l );
                         }
                         else
                         {
                             var l = (await ReadRegisterAsync(addr.ToString("X"))).ToString("X2");
                             var h = (await ReadRegisterAsync((addr - 1).ToString("X"))).ToString("X2");
                             addrstr = textEdit1.Text + ",0x" + h + l;
                             monitoringlist.Add(textEdit1.Text + "," + h + l );
                         }
                        
                         break;
                     case 2:
                         if (radioGroup1.SelectedIndex == 0)
                         {
                             var l1 = (await ReadRegisterAsync(addr.ToString("X"))).ToString("X2");
                             var mo = (await ReadRegisterAsync((addr + 1).ToString("X"))).ToString("X2");
                             var m1 = (await ReadRegisterAsync((addr + 2).ToString("X"))).ToString("X2");
                             var h1 = (await ReadRegisterAsync((addr + 3).ToString("X"))).ToString("X2");
                             addrstr = textEdit1.Text + ",0x" + h1 + m1 + mo + l1;
                             monitoringlist.Add(textEdit1.Text + "," + h1 + m1 + mo + l1 );
                         }
                         else
                         {
                             var l1 = (await ReadRegisterAsync(addr.ToString("X"))).ToString("X2");
                             var mo = (await ReadRegisterAsync((addr - 1).ToString("X"))).ToString("X2");
                             var m1 = (await ReadRegisterAsync((addr - 1).ToString("X"))).ToString("X2");
                             var h1 = (await ReadRegisterAsync((addr - 1).ToString("X"))).ToString("X2");
                             addrstr = textEdit1.Text + ",0x" + h1 + m1 + mo + l1;
                             monitoringlist.Add(textEdit1.Text + "," + h1 + m1 + mo + l1);
                         }
                         
                         break;
                     default:
                         break;
                 }
                 
                 sum++;
                 string addrstr2 = "";
                 if (!string.IsNullOrEmpty(textEdit3.Text))
                 {
                    
                     switch (radioGroup3.SelectedIndex)
                     {
                         case 0:
                             var add = (await ReadRegisterAsync(addr2.ToString("X"))).ToString("X2");
                             addrstr2 = textEdit3.Text + ",0x" + add;
                             monitoringlist.Add(textEdit3.Text + "," + add);
                             break;
                         case 1:
                             if (radioGroup1.SelectedIndex == 0)
                             {
                                 var l = (await ReadRegisterAsync(addr2.ToString("X"))).ToString("X2");
                                 var h = (await ReadRegisterAsync((addr2 + 1).ToString("X"))).ToString("X2");
                                 addrstr2 = textEdit3.Text + ",0x" + h + l;
                                 monitoringlist.Add(textEdit3.Text + "," + h + l);
                             }
                             else
                             {
                                 var l = (await ReadRegisterAsync(addr2.ToString("X"))).ToString("X2");
                                 var h = (await ReadRegisterAsync((addr2 - 1).ToString("X"))).ToString("X2");
                                 addrstr2 = textEdit3.Text + ",0x" + h + l;
                                 monitoringlist.Add(textEdit3.Text + "," + h + l);
                             }

                             break;
                         case 2:
                             if (radioGroup1.SelectedIndex == 0)
                             {
                                 var l1 = (await ReadRegisterAsync(addr2.ToString("X"))).ToString("X2");
                                 var mo = (await ReadRegisterAsync((addr2 + 1).ToString("X"))).ToString("X2");
                                 var m1 = (await ReadRegisterAsync((addr2 + 2).ToString("X"))).ToString("X2");
                                 var h1 = (await ReadRegisterAsync((addr2 + 3).ToString("X"))).ToString("X2");
                                 addrstr2 = textEdit3.Text + ",0x" + h1 + m1 + mo + l1;
                                 monitoringlist.Add(textEdit3.Text + "," + h1 + m1 + mo + l1);
                             }
                             else
                             {
                                 var l1 = (await ReadRegisterAsync(addr2.ToString("X"))).ToString("X2");
                                 var mo = (await ReadRegisterAsync((addr2 - 1).ToString("X"))).ToString("X2");
                                 var m1 = (await ReadRegisterAsync((addr2 - 2).ToString("X"))).ToString("X2");
                                 var h1 = (await ReadRegisterAsync((addr2 - 3).ToString("X"))).ToString("X2");
                                 addrstr2 = textEdit3.Text + ",0x" + h1 + m1 + mo + l1;
                                 monitoringlist.Add(textEdit3.Text + "," + h1 + m1 + mo + l1);
                             }

                             break;
                         default:
                             break;
                     }
                     
                     sum++;
                 }
                 setShowMsg(addrstr + "；\n" + addrstr2);
                 if (sum > 18)
                 {
                     memoEdit1.Text = "";
                     sum = 0;
                 }
             });
                
            }
            catch (Exception)
            {
                myTimer.Stop();
                throw;
            }
           
        }
        public void setShowMsg(string msg)
        {
            if (this.IsHandleCreated)
            {
                this.Invoke((EventHandler)(delegate
                {
                    //if (memoEdit1.Text.Length > 5000)
                    //{
                    //    memoEdit1.Text = "";
                    //}
                    //追加的形式添加到文本框末端，并滚动到最后。     
                    this.memoEdit1.Text = string.Format("{0} \r\n {2} {1}", this.memoEdit1.Text, msg, "");
                    this.memoEdit1.SelectionStart = memoEdit1.Text.Length;
                    this.memoEdit1.ScrollToCaret();

                }));
            }
        }

       

        private void button4_Click(object sender, EventArgs e)
        {
            button3.Enabled = true;
            textEdit2.Enabled = true;
            myTimer.Stop();
        }

        private void XChip_AF_Load(object sender, EventArgs e)
        {
            radioGroup3.SelectedIndex = 0;
            radioGroup2.SelectedIndex = 0;
            radioGroup1.SelectedIndex = 0;
            protractradio0.SelectedIndex = 0;
            protractradio1.SelectedIndex = 0;
            protractradio2.SelectedIndex = 0;
            protractradio3.SelectedIndex = 0;
            protractradio4.SelectedIndex = 0;
            protractradio5.SelectedIndex = 0;
            protractradio6.SelectedIndex = 0;
            protractradio7.SelectedIndex = 0;
            protractradio8.SelectedIndex = 0;
            protractradio9.SelectedIndex = 0;
            Draworder0.SelectedIndex = 0;
            Draworder1.SelectedIndex = 0;
            Draworder2.SelectedIndex = 0;
            Draworder3.SelectedIndex = 0;
            Draworder4.SelectedIndex = 0;
            Draworder5.SelectedIndex = 0;
            Draworder6.SelectedIndex = 0;
            Draworder7.SelectedIndex = 0;
            Draworder8.SelectedIndex = 0;
            Draworder9.SelectedIndex = 0;
            HIGH_PRE.Properties.Minimum = 0;
            HIGH_PRE.Properties.Maximum = 0x3FF;
            HIGH_PRE.Properties.SmallChange = 1;
        }
        //private void button5_Click(object sender, EventArgs e)
        //{
        //    chart5.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
        //    chart5.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
        //    List<int> XNumbers = new List<int>();
        //    List<int> YNumbers = new List<int>();
        //    int monitoringsum = 0;
        //    foreach (var item in monitoringlist)
        //    {
        //        YNumbers.Add(Convert.ToInt32(item,16));
        //        XNumbers.Add(monitoringsum);
        //        monitoringsum++;
        //    }
        //    int[] X = XNumbers.ToArray();
        //    int[] Y = YNumbers.ToArray();
        //    var MaxY = Y.Max() / 10;
        //    chart5.ChartAreas[0].AxisX.Interval = 10;
        //    chart5.ChartAreas[0].AxisY.Interval = MaxY>=10 ? MaxY : 10;
        //    chart5.ChartAreas[0].AxisX.Maximum = X.Max();
        //    chart5.ChartAreas[0].AxisY.Maximum = Y.Max() >= 10 ? Y.Max() : 10;

        //    chart5.Series[0].Points.DataBindXY(X, Y);
        //}


        private void button5_Click(object sender, EventArgs e)
        {
            chart5.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            chart5.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            
            
            List<string> addrlist = new List<string>();
            List<int> valuelist = new List<int>();
            foreach (var item in monitoringlist)
            {
                addrlist.Add(item.Split(',')[0]);
                valuelist.Add(Convert.ToInt32(item.Split(',')[1],16));
            }
            var divisor = addrlist.Distinct().ToList();
            double result = (double)valuelist.Count() / divisor.Count();
            int addrsum = 0;
            if (result % 1 != 0)
            {
                addrsum = (int)Math.Ceiling(result); 
            }
            else
            {
                addrsum = (int)result;

            }
            if (valuelist.Count()<= 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"文件异常,请导入正确的文件");
                return;
            }
            var MaxY = valuelist.Max() / 10;
            chart5.ChartAreas[0].AxisX.Interval = 10;
            chart5.ChartAreas[0].AxisY.Interval = MaxY>=10 ? MaxY : 10;
            chart5.ChartAreas[0].AxisX.Maximum = addrsum;
            chart5.ChartAreas[0].AxisY.Maximum = valuelist.Max() >= 10 ? valuelist.Max() : 10;

            for (int i = 0; i < divisor.Count(); i++)
            {
                int monitoringsum = 0;
                var list = monitoringlist.Where(c => c.Contains(divisor[i])).ToList();
                List<int> XNumbers = new List<int>();
                List<int> YNumbers = new List<int>();
                foreach (var item in list)
                {
                    YNumbers.Add(Convert.ToInt32(item.Split(',')[1], 16));
                    XNumbers.Add(monitoringsum);
                    monitoringsum++;
                }
                int[] X = XNumbers.ToArray();
                int[] Y = YNumbers.ToArray();
                chart5.Series[i].Points.DataBindXY(X, Y);
            }
            
        }

        private void button6_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "导出文件（*.txt）|*.txt";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "监控参数_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllLines($"{sfd.FileName}", monitoringlist);
                DevExpress.XtraEditors.XtraMessageBox.Show($"导出成功！ 文件路径：{sfd.FileName}");
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();//将打开的地址给ofd
            openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
            if (openFileDialog.ShowDialog() == DialogResult.OK)//用户是否选择确定
            {
                StreamReader sr = new StreamReader(openFileDialog.FileName);
                var aaa = Path.GetFileName(openFileDialog.FileName);
                if (!Path.GetFileName(openFileDialog.FileName).Contains("监控参数"))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show($"文件格式错误，请重新选择");
                    return;
                }
                string tempStr = string.Empty;
                List<string> tempStrList = new List<string>();
                while ((tempStr = sr.ReadLine()) != null)
                {
                    if (!tempStr.Contains("//")&&!string.IsNullOrEmpty(tempStr))
                    {
                        tempStrList.Add(tempStr);
                    }
                }
                sr.Close();
                monitoringlist = new List<string>();
                monitoringlist.AddRange(tempStrList);
                button5_Click(null, null);
            }
            

        }

        private void textEdit2_EditValueChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textEdit2.Text)) { return; }
            // 初始化Timer  
            myTimer = new System.Timers.Timer();
            // 设置Timer的间隔为50毫秒  
            myTimer.Interval = int.Parse(textEdit2.Text);
            // 设置Timer的Elapsed事件  
            myTimer.Elapsed += OnTimedEvent;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            int[] a = new int[] { 0 }; 
            chart5.Series[0].Points.DataBindXY(a, a);
            chart5.Series[1].Points.DataBindXY(a, a);
            chart5.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            chart5.ChartAreas[0].AxisY.MajorGrid.Enabled = false;


            List<string> addrlist = new List<string>();
            List<int> valuelist = new List<int>();
            foreach (var item in monitoringlist)
            {
                addrlist.Add(item.Split(',')[0]);
            }
            var divisor = addrlist.Distinct().ToList();
            if (divisor.Count() <= 1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"无地址1数据请检查或重新监控");
                return;
            }
            var listaddrsum = monitoringlist.Where(c => c.Contains(divisor[0])).ToList();
            foreach (var item in listaddrsum)
            {
                valuelist.Add(Convert.ToInt32(item.Split(',')[1], 16));
            }
            int addrsum = listaddrsum.Count();
            
            var MaxY = valuelist.Max() / 10;
            chart5.ChartAreas[0].AxisX.Interval = 10;
            chart5.ChartAreas[0].AxisY.Interval = MaxY >= 10 ? MaxY : 10;
            chart5.ChartAreas[0].AxisX.Maximum = addrsum;
            chart5.ChartAreas[0].AxisY.Maximum = valuelist.Max() >= 10 ? valuelist.Max() : 10;

            int monitoringsum = 0;
            List<int> XNumbers = new List<int>();
            List<int> YNumbers = new List<int>();
            foreach (var item in listaddrsum)
            {
                YNumbers.Add(Convert.ToInt32(item.Split(',')[1], 16));
                XNumbers.Add(monitoringsum);
                monitoringsum++;
            }
            int[] X = XNumbers.ToArray();
            int[] Y = YNumbers.ToArray();
            chart5.Series[0].Points.DataBindXY(X, Y);
            
        }

        private void button9_Click(object sender, EventArgs e)
        {
            int[] a = new int[] { 0 };
            chart5.Series[0].Points.DataBindXY(a, a);
            chart5.Series[1].Points.DataBindXY(a, a);
            chart5.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            chart5.ChartAreas[0].AxisY.MajorGrid.Enabled = false;


            List<string> addrlist = new List<string>();
            List<int> valuelist = new List<int>();
            foreach (var item in monitoringlist)
            {
                addrlist.Add(item.Split(',')[0]);
            }
            var divisor = addrlist.Distinct().ToList();
            if (divisor.Count() <= 1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"无地址2数据请检查或重新监控");
                return;
            }
            var listaddrsum = monitoringlist.Where(c => c.Contains(divisor[1])).ToList();
            foreach (var item in listaddrsum)
            {
                valuelist.Add(Convert.ToInt32(item.Split(',')[1], 16));
            }
            int addrsum = listaddrsum.Count();

            var MaxY = valuelist.Max() / 10;
            chart5.ChartAreas[0].AxisX.Interval = 10;
            chart5.ChartAreas[0].AxisY.Interval = MaxY >= 10 ? MaxY : 10;
            chart5.ChartAreas[0].AxisX.Maximum = addrsum;
            chart5.ChartAreas[0].AxisY.Maximum = valuelist.Max() >= 10 ? valuelist.Max() : 10;

            int monitoringsum = 0;
            List<int> XNumbers = new List<int>();
            List<int> YNumbers = new List<int>();
            foreach (var item in listaddrsum)
            {
                YNumbers.Add(Convert.ToInt32(item.Split(',')[1], 16));
                XNumbers.Add(monitoringsum);
                monitoringsum++;
            }
            int[] X = XNumbers.ToArray();
            int[] Y = YNumbers.ToArray();
            chart5.Series[1].Points.DataBindXY(X, Y);
        }
        List<string> protractlist0 = new List<string>();
        List<string> protractlist1 = new List<string>();
        List<string> protractlist2 = new List<string>();
        List<string> protractlist3 = new List<string>();
        List<string> protractlist4 = new List<string>();
        List<string> protractlist5 = new List<string>();
        List<string> protractlist6 = new List<string>();
        List<string> protractlist7 = new List<string>();
        List<string> protractlist8 = new List<string>();
        List<string> protractlist9 = new List<string>();
        private async void button10_Click(object sender, EventArgs e)
        {
            buffer = int.Parse(textEdit5.Text);
            List<int> Ylist = new List<int>();
            for (int i = 0; i < buffer; i++)
            {
                Ylist.Add(i);
            }
            int[] X = Ylist.ToArray();

            // 清空图表系列
            for (int i = 0; i < 10; i++)
            {
                if (chart2.Series[i].Points.Count() != 0)
                {
                    chart2.Series[i].Points.Clear();
                }
            }

            chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

            // 初始化列表
            List<string>[] protractLists = new List<string>[10];
            for (int i = 0; i < 10; i++)
            {
                protractLists[i] = new List<string>();
            }

            // 按顺序处理每个通道
            await ProcessChannelAsync(0, protractcheck0, protracttext0, protractradio0, Draworder0, protractLists[0]);
            await ProcessChannelAsync(1, protractcheck1, protracttext1, protractradio1, Draworder1, protractLists[1]);
            await ProcessChannelAsync(2, protractcheck2, protracttext2, protractradio2, Draworder2, protractLists[2]);
            await ProcessChannelAsync(3, protractcheck3, protracttext3, protractradio3, Draworder3, protractLists[3]);
            await ProcessChannelAsync(4, protractcheck4, protracttext4, protractradio4, Draworder4, protractLists[4]);
            await ProcessChannelAsync(5, protractcheck5, protracttext5, protractradio5, Draworder5, protractLists[5]);
            await ProcessChannelAsync(6, protractcheck6, protracttext6, protractradio6, Draworder6, protractLists[6]);
            await ProcessChannelAsync(7, protractcheck7, protracttext7, protractradio7, Draworder7, protractLists[7]);
            await ProcessChannelAsync(8, protractcheck8, protracttext8, protractradio8, Draworder8, protractLists[8]);
            await ProcessChannelAsync(9, protractcheck9, protracttext9, protractradio9, Draworder9, protractLists[9]);

            // 合并所有数据并计算最大值
            List<ulong> sumlist = new List<ulong>();
            for (int i = 0; i < 10; i++)
            {
                foreach (var item in protractLists[i])
                {
                    sumlist.Add(Convert.ToUInt64(item.Split(',')[1], 16));
                }
            }

            if (sumlist.Count() == 0)
            {
                return;
            }

            var MaxY = sumlist.Max();
            chart2.ChartAreas[0].AxisX.Interval = 1;
            chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
            chart2.ChartAreas[0].AxisX.Maximum = buffer;
            chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;

            // 绘制图表
            for (int i = 0; i < 10; i++)
            {
                if (GetCheckEdit(i).Checked && protractLists[i].Count > 0)
                {
                    List<ulong> data = protractLists[i].Select(item => Convert.ToUInt64(item.Split(',')[1], 16)).ToList();
                    ulong[] Y = data.ToArray();
                    chart2.Series[i].Points.DataBindXY(X, Y);
                }
            }
        }

        // 处理每个通道的通用方法
        private async Task ProcessChannelAsync(int channelIndex, DevExpress.XtraEditors.CheckEdit checkBox, DevExpress.XtraEditors.TextEdit textBox, DevExpress.XtraEditors.RadioGroup radioButton, DevExpress.XtraEditors.RadioGroup drawOrder, List<string> protractList)
        {
            if (!checkBox.Checked) return;

            if (!string.IsNullOrEmpty(textBox.Text) && textBox.Text.Length == 8)
            {
                var baseAddr = Convert.ToUInt32(textBox.Text, 16);

                switch (radioButton.SelectedIndex)
                {
                    case 0: // 8位
                        for (int i = 0; i < buffer; i++)
                        {
                            var value = await ReadRegisterAsync((baseAddr + (uint)i).ToString("X"));
                            protractList.Add($"{textBox.Text},{value:X2}");
                        }
                        break;

                    case 1: // 16位
                        if (drawOrder.SelectedIndex == 0)
                        {
                            var l = baseAddr;
                            var h = baseAddr + 1;
                            uint count = 0;
                            for (int i = 0; i < buffer; i++)
                            {
                                var highByte = await ReadRegisterAsync((h + (uint)i + count).ToString("X"));
                                var lowByte = await ReadRegisterAsync((l + (uint)i + count).ToString("X"));
                                protractList.Add($"{textBox.Text},{highByte:X2}{lowByte:X2}");
                                count++;
                            }
                        }
                        else
                        {
                            var l = baseAddr;
                            var h = baseAddr - 1;
                            uint count = 0;
                            for (int i = 0; i < buffer; i++)
                            {
                                var highByte = await ReadRegisterAsync((h + (uint)i + count).ToString("X"));
                                var lowByte = await ReadRegisterAsync((l + (uint)i + count).ToString("X"));
                                protractList.Add($"{textBox.Text},{highByte:X2}{lowByte:X2}");
                                count++;
                            }
                        }
                        break;

                    case 2: // 32位
                        if (drawOrder.SelectedIndex == 0)
                        {
                            var l1 = baseAddr;
                            var mo = baseAddr + 1;
                            var m1 = baseAddr + 2;
                            var h1 = baseAddr + 3;
                            uint count = 0;
                            for (int i = 0; i < buffer; i++)
                            {
                                var byte3 = await ReadRegisterAsync((h1 + count).ToString("X"));
                                var byte2 = await ReadRegisterAsync((m1 + count).ToString("X"));
                                var byte1 = await ReadRegisterAsync((mo + count).ToString("X"));
                                var byte0 = await ReadRegisterAsync((l1 + count).ToString("X"));
                                protractList.Add($"{textBox.Text},{byte3:X2}{byte2:X2}{byte1:X2}{byte0:X2}");
                                count += 4;
                            }
                        }
                        else
                        {
                            var l1 = baseAddr;
                            var mo = baseAddr - 1;
                            var m1 = baseAddr - 2;
                            var h1 = baseAddr - 3;
                            uint count = 0;
                            for (int i = 0; i < buffer; i++)
                            {
                                var byte3 = await ReadRegisterAsync((h1 + count).ToString("X"));
                                var byte2 = await ReadRegisterAsync((m1 + count).ToString("X"));
                                var byte1 = await ReadRegisterAsync((mo + count).ToString("X"));
                                var byte0 = await ReadRegisterAsync((l1 + count).ToString("X"));
                                protractList.Add($"{textBox.Text},{byte3:X2}{byte2:X2}{byte1:X2}{byte0:X2}");
                                count += 4;
                            }
                        }
                        break;

                    case 3: // 64位
                        if (drawOrder.SelectedIndex == 0)
                        {
                            var l1 = baseAddr;
                            var mo = baseAddr + 1;
                            var m1 = baseAddr + 2;
                            var m2 = baseAddr + 3;
                            var m3 = baseAddr + 4;
                            var m4 = baseAddr + 5;
                            var m5 = baseAddr + 6;
                            var h1 = baseAddr + 7;
                            uint count = 0;
                            for (int i = 0; i < buffer; i++)
                            {
                                var byte7 = await ReadRegisterAsync((h1 + count).ToString("X"));
                                var byte6 = await ReadRegisterAsync((m5 + count).ToString("X"));
                                var byte5 = await ReadRegisterAsync((m4 + count).ToString("X"));
                                var byte4 = await ReadRegisterAsync((m3 + count).ToString("X"));
                                var byte3 = await ReadRegisterAsync((m2 + count).ToString("X"));
                                var byte2 = await ReadRegisterAsync((m1 + count).ToString("X"));
                                var byte1 = await ReadRegisterAsync((mo + count).ToString("X"));
                                var byte0 = await ReadRegisterAsync((l1 + count).ToString("X"));
                                protractList.Add($"{textBox.Text},{byte7:X2}{byte6:X2}{byte5:X2}{byte4:X2}{byte3:X2}{byte2:X2}{byte1:X2}{byte0:X2}");
                                count += 8;
                            }
                        }
                        else
                        {
                            var l1 = baseAddr;
                            var mo = baseAddr - 1;
                            var m1 = baseAddr - 2;
                            var m2 = baseAddr - 3;
                            var m3 = baseAddr - 4;
                            var m4 = baseAddr - 5;
                            var m5 = baseAddr - 6;
                            var h1 = baseAddr - 7;
                            uint count = 0;
                            for (int i = 0; i < buffer; i++)
                            {
                                var byte7 = await ReadRegisterAsync((h1 + count).ToString("X"));
                                var byte6 = await ReadRegisterAsync((m5 + count).ToString("X"));
                                var byte5 = await ReadRegisterAsync((m4 + count).ToString("X"));
                                var byte4 = await ReadRegisterAsync((m3 + count).ToString("X"));
                                var byte3 = await ReadRegisterAsync((m2 + count).ToString("X"));
                                var byte2 = await ReadRegisterAsync((m1 + count).ToString("X"));
                                var byte1 = await ReadRegisterAsync((mo + count).ToString("X"));
                                var byte0 = await ReadRegisterAsync((l1 + count).ToString("X"));
                                protractList.Add($"{textBox.Text},{byte7:X2}{byte6:X2}{byte5:X2}{byte4:X2}{byte3:X2}{byte2:X2}{byte1:X2}{byte0:X2}");
                                count += 8;
                            }
                        }
                        break;
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请检查输入的寄存器！");
                return;
            }
        }

        // 辅助方法：根据索引获取对应的CheckEdit
        private DevExpress.XtraEditors.CheckEdit GetCheckEdit(int index)
        {
            switch (index)
            {
                case 0: return protractcheck0;
                case 1: return protractcheck1;
                case 2: return protractcheck2;
                case 3: return protractcheck3;
                case 4: return protractcheck4;
                case 5: return protractcheck5;
                case 6: return protractcheck6;
                case 7: return protractcheck7;
                case 8: return protractcheck8;
                case 9: return protractcheck9;
                default: throw new ArgumentOutOfRangeException(nameof(index));
            }
        }


        private void chart2_MouseHover(object sender, EventArgs e)
        {
            chart2.Series[0].ToolTip = $"地址1：\r\nX：#VALX\nY：#VALY";
            chart2.Series[1].ToolTip = $"地址2：\r\nX：#VALX\nY：#VALY";
            chart2.Series[2].ToolTip = $"地址3：\r\nX：#VALX\nY：#VALY";
            chart2.Series[3].ToolTip = $"地址4：\r\nX：#VALX\nY：#VALY";
            chart2.Series[4].ToolTip = $"地址5：\r\nX：#VALX\nY：#VALY";
            chart2.Series[5].ToolTip = $"地址6：\r\nX：#VALX\nY：#VALY";
            chart2.Series[6].ToolTip = $"地址7：\r\nX：#VALX\nY：#VALY";
            chart2.Series[7].ToolTip = $"地址8：\r\nX：#VALX\nY：#VALY";
            chart2.Series[8].ToolTip = $"地址9：\r\nX：#VALX\nY：#VALY";
            chart2.Series[9].ToolTip = $"地址10：\r\nX：#VALX\nY：#VALY";
        }

        private async void simpleButton8_Click(object sender, EventArgs e)
        {
            byte registerValue;

            if (!string.IsNullOrEmpty(textEdit7.Text))
            {
                registerValue = (byte)(await ReadRegisterAsync(textEdit7.Text));
            }
            else
            {
                registerValue = (byte)await ReadRegisterAsync("20006EA7"); // 0x20006ea7 的十六进制字符串
            }

            if (registerValue == 0x1)
            {
                button11.Text = "清空debugbuffer";
            }
            else
            {
                button11.Text = "开启debugbuffer";
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textEdit7.Text))
            {
                if (button11.Text == "开启debugbuffer")
                {
                    SerialSend.WriteRegister(Convert.ToUInt32(textEdit7.Text, 16), 0x1, sPortTemp);
                    button11.Text = "清空debugbuffer";
                }
                else
                {
                    SerialSend.WriteRegister(Convert.ToUInt32(textEdit7.Text, 16), 0x0, sPortTemp);
                    button11.Text = "开启debugbuffer";
                }
            }
            else
            {
                if (button11.Text == "开启debugbuffer")
                {
                    SerialSend.WriteRegister(0x20006ea7, 0x1, sPortTemp);
                    button11.Text = "清空debugbuffer";
                }
                else
                {
                    SerialSend.WriteRegister(0x20006ea7, 0x0, sPortTemp);
                    button11.Text = "开启debugbuffer";
                }
            }
            
        }

        private void tabPane1_SelectedPageIndexChanged(object sender, EventArgs e)
        {
            simpleButton8_Click(null, null);
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist0.Count()!=0)
            {
                if (protractcheck0.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }
                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion

                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion

                }
                else
                {
                    if (chart2.Series[0].Points.Count() != 0)
                    {
                        chart2.Series[0].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
            
        }

        private void button12_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "导出文件（*.txt）|*.txt";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "参数_" + DateTime.Now.ToString("yyyyMMddHHmmss")+ "_buffer数"+ buffer;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                List<string> sumlist = new List<string>();
                sumlist.AddRange(protractlist0);
                sumlist.AddRange(protractlist1);
                sumlist.AddRange(protractlist2);
                sumlist.AddRange(protractlist3);
                sumlist.AddRange(protractlist4);
                sumlist.AddRange(protractlist5);
                sumlist.AddRange(protractlist6);
                sumlist.AddRange(protractlist7);
                sumlist.AddRange(protractlist8);
                sumlist.AddRange(protractlist9);
                File.WriteAllLines($"{sfd.FileName}", sumlist);


                // 创建一个新的 Excel 工作簿  
                IWorkbook workbook = new XSSFWorkbook();
                // 创建一个工作表  
                ISheet sheet = workbook.CreateSheet("Sheet1");



                // 遍历列表并填充 Excel  
                for (int row = 0; row < protractlist0.Count + 1; row++)
                {
                    // 创建行（如果尚未存在）  
                    IRow currentRow = sheet.CreateRow(row);
                    if (row == 0)
                    {
                        if (protractlist0.Count() >= row && protractlist0.Count() != 0)
                        {
                            currentRow.CreateCell(0).SetCellValue(protractlist0[row].Split(',')[0]);
                        }
                        if (protractlist1.Count() >= row && protractlist1.Count() != 0)
                        {
                            currentRow.CreateCell(1).SetCellValue(protractlist1[row].Split(',')[0]);
                        }
                        if (protractlist2.Count() >= row && protractlist2.Count() != 0)
                        {
                            currentRow.CreateCell(2).SetCellValue(protractlist2[row].Split(',')[0]);
                        }
                        if (protractlist3.Count() >= row && protractlist3.Count() != 0)
                        {
                            currentRow.CreateCell(3).SetCellValue(protractlist3[row].Split(',')[0]);
                        }
                        if (protractlist4.Count() >= row && protractlist4.Count() != 0)
                        {
                            currentRow.CreateCell(4).SetCellValue(protractlist4[row].Split(',')[0]);
                        }
                        if (protractlist5.Count() >= row && protractlist5.Count() != 0)
                        {
                            currentRow.CreateCell(5).SetCellValue(protractlist5[row].Split(',')[0]);
                        }
                        if (protractlist6.Count() >= row && protractlist6.Count() != 0)
                        {
                            currentRow.CreateCell(6).SetCellValue(protractlist6[row].Split(',')[0]);
                        }
                        if (protractlist7.Count() >= row && protractlist7.Count() != 0)
                        {
                            currentRow.CreateCell(7).SetCellValue(protractlist7[row].Split(',')[0]);
                        }
                        if (protractlist8.Count() >= row && protractlist8.Count() != 0)
                        {
                            currentRow.CreateCell(8).SetCellValue(protractlist8[row].Split(',')[0]);
                        }
                        if (protractlist9.Count() >= row && protractlist9.Count() != 0)
                        {
                            currentRow.CreateCell(9).SetCellValue(protractlist9[row].Split(',')[0]);
                        }
                    }
                    else
                    {
                        // 填充数据  
                        if (protractlist0.Count() >= row && protractlist0.Count() != 0)
                        {
                            currentRow.CreateCell(0).SetCellValue(protractlist0[row - 1].Split(',')[1]);
                        }
                        if (protractlist1.Count() >= row && protractlist1.Count() != 0)
                        {
                            currentRow.CreateCell(1).SetCellValue(protractlist1[row - 1].Split(',')[1]);
                        }
                        if (protractlist2.Count() >= row && protractlist2.Count() != 0)
                        {
                            currentRow.CreateCell(2).SetCellValue(protractlist2[row - 1].Split(',')[1]);
                        }
                        if (protractlist3.Count() >= row && protractlist3.Count() != 0)
                        {
                            currentRow.CreateCell(3).SetCellValue(protractlist3[row - 1].Split(',')[1]);
                        }
                        if (protractlist4.Count() >= row && protractlist4.Count() != 0)
                        {
                            currentRow.CreateCell(4).SetCellValue(protractlist4[row - 1].Split(',')[1]);
                        }
                        if (protractlist5.Count() >= row && protractlist5.Count() != 0)
                        {
                            currentRow.CreateCell(5).SetCellValue(protractlist5[row - 1].Split(',')[1]);
                        }
                        if (protractlist6.Count() >= row && protractlist6.Count() != 0)
                        {
                            currentRow.CreateCell(6).SetCellValue(protractlist6[row - 1].Split(',')[1]);
                        }
                        if (protractlist7.Count() >= row && protractlist7.Count() != 0)
                        {
                            currentRow.CreateCell(7).SetCellValue(protractlist7[row - 1].Split(',')[1]);
                        }
                        if (protractlist8.Count() >= row && protractlist8.Count() != 0)
                        {
                            currentRow.CreateCell(8).SetCellValue(protractlist8[row - 1].Split(',')[1]);
                        }
                        if (protractlist9.Count() >= row && protractlist9.Count() != 0)
                        {
                            currentRow.CreateCell(9).SetCellValue(protractlist9[row - 1].Split(',')[1]);
                        }
                    }
                   
                    
                }

                // 写入到文件  
                using (FileStream file = new FileStream(sfd.FileName.Replace(".txt", ".xlsx"), FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(file);
                }

                DevExpress.XtraEditors.XtraMessageBox.Show($"导出成功！ 文件路径：{sfd.FileName}");
            }
        }

        private void checkEdit2_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist1.Count() != 0)
            {
                if (protractcheck1.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }

                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion

                }
                else
                {
                    if (chart2.Series[1].Points.Count() != 0)
                    {
                        chart2.Series[1].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private void checkEdit3_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist2.Count() != 0)
            {
                if (protractcheck2.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }
                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }

                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion
                }
                else
                {
                    if (chart2.Series[2].Points.Count() != 0)
                    {
                        chart2.Series[2].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private void checkEdit4_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist3.Count() != 0)
            {
                if (protractcheck3.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }

                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }

                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion
                }
                else
                {
                    if (chart2.Series[3].Points.Count() != 0)
                    {
                        chart2.Series[3].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();//将打开的地址给ofd
            openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
            if (openFileDialog.ShowDialog() == DialogResult.OK)//用户是否选择确定
            {
                if (!Path.GetFileName(openFileDialog.FileName).Contains("参数_"))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show($"文件格式错误，请重新选择");
                    return;
                }
                StreamReader sr = new StreamReader(openFileDialog.FileName);
                string tempStr = string.Empty;
                List<string> tempStrList = new List<string>();
                while ((tempStr = sr.ReadLine()) != null)
                {
                    if (!tempStr.Contains("//") && !string.IsNullOrEmpty(tempStr))
                    {
                        tempStrList.Add(tempStr);
                    }
                }
                sr.Close();
                List<string> addrlist = new List<string>();
                foreach (var item in tempStrList)
                {
                    addrlist.Add(item.Split(',')[0]);
                    
                }
                var divisor = addrlist.Distinct().ToList();
                if (divisor.Count() == 0|| divisor.Count() > 10)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show($"数据异常请检查导入文件");
                    return;
                }
                buffer = int.Parse(textEdit5.Text);
                protractlist0 = new List<string>();
                protractlist1 = new List<string>();
                protractlist2 = new List<string>();
                protractlist3 = new List<string>();
                protractlist4 = new List<string>();
                protractlist5 = new List<string>();
                protractlist6 = new List<string>();
                protractlist7 = new List<string>();
                protractlist8 = new List<string>();
                protractlist9 = new List<string>();
                switch (divisor.Count())
                {
                    case 1:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = null;
                        protracttext2.Text = null;
                        protracttext3.Text = null;
                        protracttext4.Text = null;
                        protracttext5.Text = null;
                        protracttext6.Text = null;
                        protracttext7.Text = null;
                        protracttext8.Text = null;
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = false;
                        protractcheck2.Checked = false;
                        protractcheck3.Checked = false;
                        protractcheck4.Checked = false;
                        protractcheck5.Checked = false;
                        protractcheck6.Checked = false;
                        protractcheck7.Checked = false;
                        protractcheck8.Checked = false;
                        protractcheck9.Checked = false;
                        break;
                    case 2:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = null;
                        protracttext3.Text = null;
                        protracttext4.Text = null;
                        protracttext5.Text = null;
                        protracttext6.Text = null;
                        protracttext7.Text = null;
                        protracttext8.Text = null;
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = false;
                        protractcheck3.Checked = false;
                        protractcheck4.Checked = false;
                        protractcheck5.Checked = false;
                        protractcheck6.Checked = false;
                        protractcheck7.Checked = false;
                        protractcheck8.Checked = false;
                        protractcheck9.Checked = false;
                        break;
                    case 3:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protractlist2.AddRange(tempStrList.Where(c => c.Contains(divisor[2])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = divisor[2];
                        protracttext3.Text = null;
                        protracttext4.Text = null;
                        protracttext5.Text = null;
                        protracttext6.Text = null;
                        protracttext7.Text = null;
                        protracttext8.Text = null;
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = true;
                        protractcheck3.Checked = false;
                        protractcheck4.Checked = false;
                        protractcheck5.Checked = false;
                        protractcheck6.Checked = false;
                        protractcheck7.Checked = false;
                        protractcheck8.Checked = false;
                        protractcheck9.Checked = false;
                        break;
                    case 4:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protractlist2.AddRange(tempStrList.Where(c => c.Contains(divisor[2])).ToList());
                        protractlist3.AddRange(tempStrList.Where(c => c.Contains(divisor[3])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = divisor[2];
                        protracttext3.Text = divisor[3];
                        protracttext4.Text = null;
                        protracttext5.Text = null;
                        protracttext6.Text = null;
                        protracttext7.Text = null;
                        protracttext8.Text = null;
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = true;
                        protractcheck3.Checked = true;
                        protractcheck4.Checked = false;
                        protractcheck5.Checked = false;
                        protractcheck6.Checked = false;
                        protractcheck7.Checked = false;
                        protractcheck8.Checked = false;
                        protractcheck9.Checked = false;

                        break;
                    case 5:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protractlist2.AddRange(tempStrList.Where(c => c.Contains(divisor[2])).ToList());
                        protractlist3.AddRange(tempStrList.Where(c => c.Contains(divisor[3])).ToList());
                        protractlist4.AddRange(tempStrList.Where(c => c.Contains(divisor[4])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = divisor[2];
                        protracttext3.Text = divisor[3];
                        protracttext4.Text = divisor[4];
                        protracttext5.Text = null;
                        protracttext6.Text = null;
                        protracttext7.Text = null;
                        protracttext8.Text = null;
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = true;
                        protractcheck3.Checked = true;
                        protractcheck4.Checked = true;
                        protractcheck5.Checked = false;
                        protractcheck6.Checked = false;
                        protractcheck7.Checked = false;
                        protractcheck8.Checked = false;
                        protractcheck9.Checked = false;

                        break;
                    case 6:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protractlist2.AddRange(tempStrList.Where(c => c.Contains(divisor[2])).ToList());
                        protractlist3.AddRange(tempStrList.Where(c => c.Contains(divisor[3])).ToList());
                        protractlist4.AddRange(tempStrList.Where(c => c.Contains(divisor[4])).ToList());
                        protractlist5.AddRange(tempStrList.Where(c => c.Contains(divisor[5])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = divisor[2];
                        protracttext3.Text = divisor[3];
                        protracttext4.Text = divisor[4];
                        protracttext5.Text = divisor[5];
                        protracttext6.Text = null;
                        protracttext7.Text = null;
                        protracttext8.Text = null;
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = true;
                        protractcheck3.Checked = true;
                        protractcheck4.Checked = true;
                        protractcheck5.Checked = true;
                        protractcheck6.Checked = false;
                        protractcheck7.Checked = false;
                        protractcheck8.Checked = false;
                        protractcheck9.Checked = false;

                        break;
                    case 7:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protractlist2.AddRange(tempStrList.Where(c => c.Contains(divisor[2])).ToList());
                        protractlist3.AddRange(tempStrList.Where(c => c.Contains(divisor[3])).ToList());
                        protractlist4.AddRange(tempStrList.Where(c => c.Contains(divisor[4])).ToList());
                        protractlist5.AddRange(tempStrList.Where(c => c.Contains(divisor[5])).ToList());
                        protractlist6.AddRange(tempStrList.Where(c => c.Contains(divisor[6])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = divisor[2];
                        protracttext3.Text = divisor[3];
                        protracttext4.Text = divisor[4];
                        protracttext5.Text = divisor[5];
                        protracttext6.Text = divisor[6];
                        protracttext7.Text = null;
                        protracttext8.Text = null;
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = true;
                        protractcheck3.Checked = true;
                        protractcheck4.Checked = true;
                        protractcheck5.Checked = true;
                        protractcheck6.Checked = true;
                        protractcheck7.Checked = false;
                        protractcheck8.Checked = false;
                        protractcheck9.Checked = false;

                        break;
                    case 8:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protractlist2.AddRange(tempStrList.Where(c => c.Contains(divisor[2])).ToList());
                        protractlist3.AddRange(tempStrList.Where(c => c.Contains(divisor[3])).ToList());
                        protractlist4.AddRange(tempStrList.Where(c => c.Contains(divisor[4])).ToList());
                        protractlist5.AddRange(tempStrList.Where(c => c.Contains(divisor[5])).ToList());
                        protractlist6.AddRange(tempStrList.Where(c => c.Contains(divisor[6])).ToList());
                        protractlist7.AddRange(tempStrList.Where(c => c.Contains(divisor[7])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = divisor[2];
                        protracttext3.Text = divisor[3];
                        protracttext4.Text = divisor[4];
                        protracttext5.Text = divisor[5];
                        protracttext6.Text = divisor[6];
                        protracttext7.Text = divisor[7];
                        protracttext8.Text = null;
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = true;
                        protractcheck3.Checked = true;
                        protractcheck4.Checked = true;
                        protractcheck5.Checked = true;
                        protractcheck6.Checked = true;
                        protractcheck7.Checked = true;
                        protractcheck8.Checked = false;
                        protractcheck9.Checked = false;

                        break;
                    case 9:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protractlist2.AddRange(tempStrList.Where(c => c.Contains(divisor[2])).ToList());
                        protractlist3.AddRange(tempStrList.Where(c => c.Contains(divisor[3])).ToList());
                        protractlist4.AddRange(tempStrList.Where(c => c.Contains(divisor[4])).ToList());
                        protractlist5.AddRange(tempStrList.Where(c => c.Contains(divisor[5])).ToList());
                        protractlist6.AddRange(tempStrList.Where(c => c.Contains(divisor[6])).ToList());
                        protractlist7.AddRange(tempStrList.Where(c => c.Contains(divisor[7])).ToList());
                        protractlist8.AddRange(tempStrList.Where(c => c.Contains(divisor[8])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = divisor[2];
                        protracttext3.Text = divisor[3];
                        protracttext4.Text = divisor[4];
                        protracttext5.Text = divisor[5];
                        protracttext6.Text = divisor[6];
                        protracttext7.Text = divisor[7];
                        protracttext8.Text = divisor[8];
                        protracttext9.Text = null;
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = true;
                        protractcheck3.Checked = true;
                        protractcheck4.Checked = true;
                        protractcheck5.Checked = true;
                        protractcheck6.Checked = true;
                        protractcheck7.Checked = true;
                        protractcheck8.Checked = true;
                        protractcheck9.Checked = false;

                        break;
                    case 10:
                        protractlist0.AddRange(tempStrList.Where(c => c.Contains(divisor[0])).ToList());
                        protractlist1.AddRange(tempStrList.Where(c => c.Contains(divisor[1])).ToList());
                        protractlist2.AddRange(tempStrList.Where(c => c.Contains(divisor[2])).ToList());
                        protractlist3.AddRange(tempStrList.Where(c => c.Contains(divisor[3])).ToList());
                        protractlist4.AddRange(tempStrList.Where(c => c.Contains(divisor[4])).ToList());
                        protractlist5.AddRange(tempStrList.Where(c => c.Contains(divisor[5])).ToList());
                        protractlist6.AddRange(tempStrList.Where(c => c.Contains(divisor[6])).ToList());
                        protractlist7.AddRange(tempStrList.Where(c => c.Contains(divisor[7])).ToList());
                        protractlist8.AddRange(tempStrList.Where(c => c.Contains(divisor[8])).ToList());
                        protractlist9.AddRange(tempStrList.Where(c => c.Contains(divisor[9])).ToList());
                        protracttext0.Text = divisor[0];
                        protracttext1.Text = divisor[1];
                        protracttext2.Text = divisor[2];
                        protracttext3.Text = divisor[3];
                        protracttext4.Text = divisor[4];
                        protracttext5.Text = divisor[5];
                        protracttext6.Text = divisor[6];
                        protracttext7.Text = divisor[7];
                        protracttext8.Text = divisor[8];
                        protracttext9.Text = divisor[9];
                        protractcheck0.Checked = true;
                        protractcheck1.Checked = true;
                        protractcheck2.Checked = true;
                        protractcheck3.Checked = true;
                        protractcheck4.Checked = true;
                        protractcheck5.Checked = true;
                        protractcheck6.Checked = true;
                        protractcheck7.Checked = true;
                        protractcheck8.Checked = true;
                        protractcheck9.Checked = true;

                        break;
                    default:
                        break;
                }
                ProtractCheckedChanged();
            }
        }
        public void ProtractCheckedChanged()
        {
            checkEdit1_CheckedChanged(null, null);
            checkEdit2_CheckedChanged(null, null);
            checkEdit3_CheckedChanged(null, null);
            checkEdit4_CheckedChanged(null, null);
            protractcheck4_CheckedChanged(null, null);
            protractcheck5_CheckedChanged(null, null);
            protractcheck6_CheckedChanged(null, null);
            protractcheck7_CheckedChanged(null, null);
            protractcheck8_CheckedChanged(null, null);
            protractcheck9_CheckedChanged(null, null);
        }
        private void chart5_MouseHover(object sender, EventArgs e)
        {
            chart5.Series[0].ToolTip = $"地址1：\r\nX：#VALX\nY：#VALY";
            chart5.Series[1].ToolTip = $"地址2：\r\nX：#VALX\nY：#VALY";
        }

        private void protractcheck4_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist4.Count() != 0)
            {
                if (protractcheck4.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }

                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion
                }
                else
                {
                    if (chart2.Series[4].Points.Count() != 0)
                    {
                        chart2.Series[4].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private void protractcheck5_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist5.Count() != 0)
            {
                if (protractcheck5.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }
                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion
                }
                else
                {
                    if (chart2.Series[5].Points.Count() != 0)
                    {
                        chart2.Series[5].Points.Clear(); 
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private void protractcheck6_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist6.Count() != 0)
            {
                if (protractcheck6.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }
                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion
                }
                else
                {
                    if (chart2.Series[6].Points.Count() != 0)
                    {
                        chart2.Series[6].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private void protractcheck7_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist7.Count() != 0)
            {
                if (protractcheck7.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }

                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion
                }
                else
                {
                    if (chart2.Series[7].Points.Count() != 0)
                    {
                        chart2.Series[7].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private async void simpleButton9_Click(object sender, EventArgs e)
        {
            Triggerflags.Text = (await GetAFRegister("Triggerflags")).ToString("X2");
            var Triggerflagsbitlist = GetSetBitsPositions(Triggerflags.Text);
            for (int i = 0; i < 8; i++)
            {
                var triggen = this.Controls.Find("triggen" + i, true);
                if (Triggerflagsbitlist.Any(c=>c == i))
                {
                    (triggen[0] as CheckEdit).Checked = true;
                    (triggen[0] as CheckEdit).ForeColor = Color.Red;
                }
                else
                {
                    (triggen[0] as CheckEdit).Checked = false;
                    (triggen[0] as CheckEdit).ForeColor = Color.Black;
                }            }
        }

        public static List<int> GetSetBitsPositions(string number)
        {
            List<int> positions = new List<int>();
            int numberint = Convert.ToInt32(number, 16);
            // 循环遍历从0到7的每一位（因为是16进制的两位数，最多8位）  
            for (int i = 0; i < 8; i++)
            {
                if ((numberint & (1 << i)) != 0)
                {
                    positions.Add(i);
                }
            }
            return positions;
        }

        private async void Enableen0_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            theenablebit.Text = (await  GetAFRegister("theenablebit")).ToString("X2");
            var chk = sender as CheckEdit;
            var bit = chk.Tag;
            int addrval = SetBitValue(theenablebit.Text, int.Parse(bit.ToString()), chk.Checked);
            if (chk.Checked)
            {
                chk.ForeColor = Color.Red;
            }
            else
            {
                chk.ForeColor = Color.Black;
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{theenablebit.Name}".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{theenablebit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, addrval.ToString("X2"));
                SetAfRegister(model, Val);
            }
            isRead = true;
            theenablebit.Text = addrval.ToString("X2");
            isRead = false;
        }
        public int SetBitValue(string currentValue, int bitValue, bool isOne)
        {
            if (isOne)
            {
                return Convert.ToInt32(currentValue, 16) | (1 << bitValue);
            }
            else
            {
                return Convert.ToInt32(currentValue, 16) & ~(1 << bitValue);
            }
        }

        private async void simpleButton10_Click(object sender, EventArgs e)
        {
            // 异步读取 GainReadOnly 相关的四个寄存器
            var byte53 = await ReadRegisterAsync("20000153");
            var byte52 = await ReadRegisterAsync("20000152");
            var byte51 = await ReadRegisterAsync("20000151");
            var byte50 = await ReadRegisterAsync("20000150");

            // 异步读取 Max_Gain 相关的两个寄存器
            var byteD3 = await ReadRegisterAsync("200000D3");
            var byteD2 = await ReadRegisterAsync("200000D2");

            // 组合 GainReadOnly 的值
            var GainReadOnly = Convert.ToInt32(byte53.ToString("X2") + byte52.ToString("X2"), 16)
                             + Convert.ToInt32(byte51.ToString("X2") + byte50.ToString("X2"), 16);

            // 组合 Max_Gain 的值
            var Max_Gain = Convert.ToInt32(byteD3.ToString("X2") + byteD2.ToString("X2"), 16);

            if (GainReadOnly == Max_Gain)
            {
                textEdit6.Text = "night";
            }
            else
            {
                textEdit6.Text = "day";
            }
        }

        private void ctthill_th_dn_night_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;

            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
        }

        private void ctthill_th_dn_night_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ctthill_th_dn_night_Leave(sender, null);
            }
        }

        private void winstartY_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            MotorCurrentRedraw();
        }

        private void winwidth_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                winstartY_Leave(sender, null);
            }
        }

        private void MotorFullRange_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            if (string.IsNullOrEmpty(MotorFullRange.Text)) return;
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{MotorFullRange.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{MotorFullRange.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, MotorFullRange.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{MotorFullRange.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{MotorFullRange.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, MotorFullRange.Text);
                SetAfRegister(model, Val);
            }
        }

        private void MotorOffsetMin_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            if (string.IsNullOrEmpty(MotorOffsetMin.Text)) return;
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{ MotorOffsetMin.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{ MotorOffsetMin.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, MotorOffsetMin.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{ MotorOffsetMin.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{ MotorOffsetMin.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, MotorOffsetMin.Text);
                SetAfRegister(model, Val);
            }

        }

        private void MotorFullRange_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                MotorFullRange_Leave(sender, null);
            }
        }

        private void DACMin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DACMin_Leave(sender, null);
            }
        }

        private void protractcheck8_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist8.Count() != 0)
            {
                if (protractcheck8.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }

                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion
                }
                else
                {
                    if (chart2.Series[8].Points.Count() != 0)
                    {
                        chart2.Series[8].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private void protractcheck9_CheckedChanged(object sender, EventArgs e)
        {
            if (protractlist9.Count() != 0)
            {
                if (protractcheck9.Checked)
                {
                    List<int> Ylist = new List<int>();
                    for (int i = 0; i < buffer; i++)
                    {
                        Ylist.Add(i);
                    }
                    int[] X = Ylist.ToArray();
                    chart2.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
                    chart2.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

                    #region 数据统计
                    List<int> sumlist = new List<int>();
                    if (protractcheck0.Checked)
                    {
                        for (int i = 0; i < protractlist0.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist0[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck1.Checked)
                    {
                        for (int i = 0; i < protractlist1.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist1[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck2.Checked)
                    {
                        for (int i = 0; i < protractlist2.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist2[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck3.Checked)
                    {
                        for (int i = 0; i < protractlist3.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist3[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck4.Checked)
                    {
                        for (int i = 0; i < protractlist4.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist4[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck5.Checked)
                    {
                        for (int i = 0; i < protractlist5.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist5[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck6.Checked)
                    {
                        for (int i = 0; i < protractlist6.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist6[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck7.Checked)
                    {
                        for (int i = 0; i < protractlist7.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist7[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck8.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist8[i].Split(',')[1], 16));
                        }
                    }
                    if (protractcheck9.Checked)
                    {
                        for (int i = 0; i < protractlist8.Count(); i++)
                        {
                            sumlist.Add(Convert.ToInt32(protractlist9[i].Split(',')[1], 16));
                        }
                    }

                    if (sumlist.Count() == 0)
                    {
                        return;
                    }
                    #endregion
                    var MaxY = sumlist.Max();
                    chart2.ChartAreas[0].AxisX.Interval = 1;
                    chart2.ChartAreas[0].AxisY.Interval = MaxY / 10 >= 10 ? MaxY / 10 : 10;
                    chart2.ChartAreas[0].AxisX.Maximum = buffer;
                    chart2.ChartAreas[0].AxisY.Maximum = sumlist.Max() >= 10 ? sumlist.Max() : 10;
                    #region 曲线图赋值
                    if (protractcheck0.Checked)
                    {
                        List<int> intprotractlist0 = new List<int>();
                        foreach (var item in protractlist0)
                        {
                            intprotractlist0.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist0.ToArray();
                        chart2.Series[0].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck1.Checked)
                    {
                        List<int> intprotractlist1 = new List<int>();
                        foreach (var item in protractlist1)
                        {
                            intprotractlist1.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist1.ToArray();
                        chart2.Series[1].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck2.Checked)
                    {
                        List<int> intprotractlist2 = new List<int>();
                        foreach (var item in protractlist2)
                        {
                            intprotractlist2.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist2.ToArray();
                        chart2.Series[2].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck3.Checked)
                    {
                        List<int> intprotractlist3 = new List<int>();
                        foreach (var item in protractlist3)
                        {
                            intprotractlist3.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist3.ToArray();
                        chart2.Series[3].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck4.Checked)
                    {
                        List<int> intprotractlist4 = new List<int>();
                        foreach (var item in protractlist4)
                        {
                            intprotractlist4.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist4.ToArray();
                        chart2.Series[4].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck5.Checked)
                    {
                        List<int> intprotractlist5 = new List<int>();
                        foreach (var item in protractlist5)
                        {
                            intprotractlist5.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist5.ToArray();
                        chart2.Series[5].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck6.Checked)
                    {
                        List<int> intprotractlist6 = new List<int>();
                        foreach (var item in protractlist6)
                        {
                            intprotractlist6.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist6.ToArray();
                        chart2.Series[6].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck7.Checked)
                    {
                        List<int> intprotractlist7 = new List<int>();
                        foreach (var item in protractlist7)
                        {
                            intprotractlist7.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist7.ToArray();
                        chart2.Series[7].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck8.Checked)
                    {
                        List<int> intprotractlist8 = new List<int>();
                        foreach (var item in protractlist8)
                        {
                            intprotractlist8.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist8.ToArray();
                        chart2.Series[8].Points.DataBindXY(X, Y);
                    }
                    if (protractcheck9.Checked)
                    {
                        List<int> intprotractlist9 = new List<int>();
                        foreach (var item in protractlist9)
                        {
                            intprotractlist9.Add(Convert.ToInt32(item.Split(',')[1], 16));
                        }
                        int[] Y = intprotractlist9.ToArray();
                        chart2.Series[9].Points.DataBindXY(X, Y);
                    }
                    #endregion
                }
                else
                {
                    if (chart2.Series[9].Points.Count() != 0)
                    {
                        chart2.Series[9].Points.Clear();
                        ProtractCheckedChanged();
                    }
                }
            }
        }

        private void counthv1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                counthv1_Leave(sender, null);
            }
        }

        private void counthv1_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
        }

        private void hv_thre1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                counthv1_Leave(sender, null);
            }
        }

        private void hv_thre1_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            string Temp = txtEdit.Text;
            if (string.IsNullOrEmpty(Temp))
                return;
            if (Convert.ToUInt32(Temp, 16) > 0x7ff)
            {
                txtEdit.Text = Temp = "7FF";
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
        }

        private void simpleButton11_Click(object sender, EventArgs e)
        {
            List<string> NameList = new List<string>();
            for (int i = 0; i < XChipAf.Count; i++)
            {
                var type = AppHelper.NameTypeToString(XChipAf[i].NameType);
                //加上单选框的_en
                if (XChipAf[i].ControlType == "1")
                {
                    type = XChipAf[i].NameType;
                }
                var col = this.Controls.Find(type, true);
                foreach (var item in col)
                {
                    if (NameList.Exists(c => c.Contains(type)))
                    {
                        continue;
                    }
                    else
                    {

                        //过滤掉指定寄存器
                        if (!item.Name.ToString().Contains("counthv") && !item.Name.ToString().Contains("hv_thre"))
                        {
                            continue;
                        }
                        if (item is TextEdit)
                        {

                            var nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            if (nList.Count == 1)
                            {
                                var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                            }
                            else
                            {
                                var listsum = nList.Select(c => c.Address).Distinct().ToList();
                                string Val = string.Empty;
                                if (1 == listsum.Count())
                                {

                                }
                                else
                                {

                                }

                                //这里默认为是有多个寄存器  一个文本框的情况进行处理
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                                }
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                                }
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                                item.Text = Val;
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipAf.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                            }
                        }


                    }
                }
                NameList.Add(type);
            }
        }

        private void HIGH_PRE_EditValueChanged(object sender, EventArgs e)
        {
            manualpos.Text = HIGH_PRE.Value.ToString("X2");
        }

        private void manualpos_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                manualpos_Leave(sender, null);
            }

        }

        private void manualpos_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            if (string.IsNullOrEmpty(manualpos.Text)) return;
            if (Convert.ToUInt32(manualpos.Text, 16) > 0x3ff)
            {
                HIGH_PRE.Value = 0x3ff;
            }
            else
            {
                HIGH_PRE.Value = Convert.ToInt32(manualpos.Text, 16);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{ manualpos.Name}_h".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{ manualpos.Name}_h".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, manualpos.Text);
                SetAfRegister(model, Val);
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"{ manualpos.Name}_l".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"{ manualpos.Name}_l".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, manualpos.Text);
                SetAfRegister(model, Val);
            }
        }

        private void AFModeCBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AFModeCBox_Leave(sender, null);
            }
        }

        private void AFModeCBox_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as System.Windows.Forms.ComboBox;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (Convert.ToUInt32(txtEdit.Text,16)== 2)
            {
                HIGH_PRE.Enabled = true;
                manualpos.Enabled = true;
            }
            else
            {
                HIGH_PRE.Enabled = false;
                manualpos.Enabled = false;
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"AF_Mode".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"AF_Mode".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
        }

        private void AF_Mode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as System.Windows.Forms.ComboBox;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (Convert.ToUInt32(txtEdit.Text, 16) == 2)
            {
                HIGH_PRE.Enabled = true;
                manualpos.Enabled = true;
            }
            else
            {
                HIGH_PRE.Enabled = false;
                manualpos.Enabled = false;
            }
            if (XChipAf.Exists(c => c.NameType.ToLower() == $"AF_Mode".ToLower()))
            {
                var model = XChipAf.Find(c => c.NameType.ToLower() == $"AF_Mode".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetAfRegister(model, Val);
            }
        }

        private void HIGH_PRE_MouseUp(object sender, MouseEventArgs e)
        {
            manualpos_Leave(sender, null);
        }
    }
}
